<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/15
 * Time: 20:15
 */
 
function userState() {
    $user_id = session('user_id');
    $user = \Lib\Api\UserApi::getInfo(array("id"=>$user_id), "state");
    $url = false;
    if ($user["state"] == 1) {
        // $this->display("shopping/index");
        $domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
        $web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
        // $this->success('',$domain_url.$web_site_dir."/shopping/index");
        $url = $domain_url.$web_site_dir."/shopping/index";
    }
    return $url;
}

function isLogin() {
    $url = false;
    $domain_url = C('TMPL_PARSE_STRING.__DOMAINURL__');
    $web_site_dir = C('TMPL_PARSE_STRING.__WEBSITEDIR__');
    if (empty(session('user_id')) && empty(session("mobile_phone"))) {
        $url = $domain_url.$web_site_dir."/index/login";
    } else {
        $user_id = session('user_id');
        $user = \Lib\Api\UserApi::getInfo(array("id"=>$user_id));
        if (empty($user['mobile_phone'])) {
            $url = $domain_url.$web_site_dir."/index/bind_mobile_phone";
        }
    }
    return $url;
}

function getMenuByAdmin($manager_id, $manager_name) {
    //根据管理员读取可访问菜单
    $model = M();
    $where['m.id'] = $manager_id;
    $where['sm.isUse'] = 1;
    //PID分组
    $list = $model->table('fs_organization m')
        // ->join('left join fs_organization o on o.id = m.organization_id')
        ->join('left join fs_organization_role mr on m.id = mr.organization_id')
        ->join('left join fs_role r on mr.role_id = r.id')
        ->join('left outer join fs_role_sys_menu rsm on r.id = rsm.role_id')
        ->join('left outer join fs_sys_menu sm on rsm.menu_id = sm.id')
        //->field('r.name, sm.name, m.id')
        ->field('sm.pid')
        ->group('sm.pid')
        ->where($where)
        ->order('sm.sort, sm.id asc')
        ->select();
    $ids = '';
    for ($i= 0;$i< count($list); $i++){
        $str= $list[$i];
        foreach ($str as $k=>$v) {
            $ids =  $ids . $v . ',';
        }
    }
    $ids = mb_substr($ids, 0, mb_strlen($ids) - 1);
    $map['id']=array('in', $ids);
    $list['parentmenu'] = $model->table('fs_sys_menu')->where($map)->order('sort asc')->select();

    $list['menus'] = $model->table('fs_organization m')
        // ->join('left join fs_organization o on o.id = m.organization_id')
        ->join('left join fs_organization_role mr on m.id = mr.organization_id')
        ->join('left join fs_role r on mr.role_id = r.id')
        ->join('left outer join fs_role_sys_menu rsm on r.id = rsm.role_id')
        ->join('left outer join fs_sys_menu sm on rsm.menu_id = sm.id')
        //->field('r.name, sm.name, m.id')
        ->field('sm.*')
        ->where($where)
        ->order('sm.sort, sm.id asc')
        ->select();

    return $list;
}

/**
 * 分页帮助函数
 */
function pageHelper($page_size, $page_num, $list, $total) {
    $left_offset = 4;
    $right_offset = 3;
    $page_count = intval($total / $page_size);
    if ($page_count < 1)
        $page_count = 1;

    if ($total > $page_size && ($total % $page_size) > 0)
        $page_count++;

    $navigatepageNums = array();
    $navigatepage = $left_offset+$right_offset+1;
    if ($navigatepage > $page_count) {
        $navigatepage = $page_count;
    }

    $firstPage = 1;
    if ($page_num - $left_offset > 0) {
        $firstPage = $page_num - $left_offset;
        if ($firstPage > ($page_count - $navigatepage)) {
            $firstPage = $page_count - $navigatepage+1;
        }
    }
    $lastPage = $page_count;
    if ($page_num + $right_offset <= $page_count) {
        $lastPage = $page_num + $right_offset;
        if ($lastPage < $navigatepage) {
            $lastPage = $navigatepage;
        }
    }

    $temp_nums = $firstPage;
    for ($i=0; $i<$navigatepage; $i++) {
        array_push($navigatepageNums, $temp_nums);
        $temp_nums++;
    }


    $startRow = 1;
    if ($page_num > 1)
        $startRow = $page_size * ($page_num - 1) + 1;
    if ($startRow == 0)
        $startRow = 1;
    if ($total == 0)
        $startRow = 0;

    $endRow = $page_size * $page_num;
    if ($endRow > $total)
        $endRow = $total;

    $data['list'] = $list;
    $data['total'] = $total;
    $data['navigatepageNums'] = $navigatepageNums;
    $data['startRow'] = $startRow;
    $data['endRow'] = $endRow;
    $data['firstPage'] = $firstPage;
    $data['lastPage'] = $lastPage;
    $data['pageNum'] = $page_num;
    $data['pageSize'] = $page_size;

    return $data;
}

/**
 * 获取用户真实 IP
 */
function getIP()
{
    static $realip;
    if (isset($_SERVER)){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}

function jquery_save_img()
{
    $arrType=array('image/jpg','image/gif','image/png','image/bmp','image/pjpeg','image/jpeg');
    $max_size='500000000000';      // 最大文件限制（单位：byte）
    $upfile='./uploads'; //图片目录路径
    $file=$_FILES['files'];

    /*
    echo 'filename:'.$file['tmp_name'].';<br />';
    echo 'size:'.$file['size'].';<br />';
    echo 'type:'.$file['type'].';<br />';
    echo 'name:'.$file['name'].';<br />';
    */

    if($_SERVER['REQUEST_METHOD']=='POST'){ //判断提交方式是否为POST
        if(!is_uploaded_file($file['tmp_name'])){ //判断上传文件是否存在
            echo "<font color='#FF0000'>文件不存在！</font>";
            exit;
        }

        if($file['size']>$max_size){  //判断文件大小是否大于500000字节
            echo "<font color='#FF0000'>上传文件太大！</font>";
            exit;
        }
        if(!in_array($file['type'],$arrType)){  //判断图片文件的格式
            echo "<font color='#FF0000'>上传文件格式不对！</font>xxx:".$file['type'];
            exit;
        }
        if(!file_exists($upfile)){  // 判断存放文件目录是否存在
            mkdir($upfile,0777,true);
        }
        $imageSize=getimagesize($file['tmp_name']);
        $img=$imageSize[0].'*'.$imageSize[1];
        $fname=$file['name'];
        $ftype=explode('.',$fname);
        $picName=$upfile."/cloudy".$fname;

        if(file_exists($picName)){
            //echo "<font color='#FF0000'>同文件名已存在！</font>";
            //exit;
        }
        if(!move_uploaded_file($file['tmp_name'],$picName)){
            echo "<font color='#FF0000'>移动文件出错！</font>";
            exit;
        }
        else{
            /*
                echo "<font color='#FF0000'>图片文件上传成功！</font><br/>";
                echo "<font color='#0000FF'>图片大小：$img</font><br/>";
                echo "图片预览：<br><div style='border:#F00 1px solid; width:200px;height:200px'>
                <img src=\"".$picName."\" width=200px height=200px>".$fname."</div>";
            */
            echo '{"imgurl":"http://localhost/uploads/cloudy'.$fname.'"}';
        }
    }

}

/**
 * 生成二维码
 * @param  string  $url  url连接
 * @param  integer $size 尺寸 纯数字
 */
function qrcode($url,$size=4, $outfile=false){
    Vendor('Phpqrcode.phpqrcode');
    QRcode::png($url,$outfile,QR_ECLEVEL_L,$size,2,false,0xFFFFFF,0x000000);
}

function check_verify($code, $id = ''){
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/**
 * 获取一定范围内的随机数字
 * 跟rand()函数的区别是 位数不足补零 例如
 * rand(1,9999)可能会得到 465
 * rand_number(1,9999)可能会得到 0465  保证是4位的
 * @param integer $min 最小值
 * @param integer $max 最大值
 * @return string
 */
function rand_number ($min=1, $max=9999) {
    return sprintf("%0".strlen($max)."d", mt_rand($min,$max));
}

/**
 * 生成一定数量的随机数，并且不重复
 * @param integer $number 数量
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @return string
 */
function build_count_rand ($number,$length=4,$mode=1) {
    if($mode==1 && $length<strlen($number) ) {
        //不足以生成一定数量的不重复数字
        return false;
    }
    $rand   =  array();
    for($i=0; $i<$number; $i++) {
        $rand[] = rand_string($length,$mode);
    }
    $unqiue = array_unique($rand);
    if(count($unqiue)==count($rand)) {
        return $rand;
    }
    $count   = count($rand)-count($unqiue);
    for($i=0; $i<$count*3; $i++) {
        $rand[] = rand_string($length,$mode);
    }
    $rand = array_slice(array_unique ($rand),0,$number);
    return $rand;
}

/**
 * 生成不重复的随机数
 * @param  int $start  需要生成的数字开始范围
 * @param  int $end 结束范围
 * @param  int $length 需要生成的随机数个数
 * @return array       生成的随机数
 */
function get_rand_number($start=1,$end=10,$length=4){
    $connt=0;
    $temp=array();
    while($connt<$length){
        $temp[]=rand($start,$end);
        $data=array_unique($temp);
        $connt=count($data);
    }
    sort($data);
    return $data;
}

/**
 * 获取当前星期
 */
function getWeek(){
    $week = date('w');
    switch($week){
        case 1:
            return "mon";
            break;
        case 2:
            return "tue";
            break;
        case 3:
            return "wed";
            break;
        case 4:
            return "thu";
            break;
        case 5:
            return "fri";
            break;
        case 6:
            return "sat";
            break;
        case 0:
            return "sun";
            break;
    }
}

/**
 * 检测是否手机端登录
 */
function check_wap() {
    // 先检查是否为wap代理，准确度高
    if(stristr($_SERVER['HTTP_VIA'],"wap")){
        return 0;
    }
    // 检查浏览器是否接受 WML.
    elseif(strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0){
        return 0;
    }
    //检查USER_AGENT
    elseif(preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])){
        return 0;
    }
    else{
        return 1;
    }
}